﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using PServiceBus.WindowsPhone;

namespace WP7ChatApp {
    public partial class MainPage : PhoneApplicationPage {
        
        public MainPage() {
            InitializeComponent();
        }

        
        public class ChatTopic {
            public string UserName { get; set; }
            public string Message { get; set; }
        }

        private void sendBtn_Click(object sender, RoutedEventArgs e) {
            PSBClient.Publish(new ChatTopic { Message = txtMessage.Text, UserName = "Windows Phone" });
            txtMessage.Text = string.Empty;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) {
            PSBClient.Subscribe<ChatTopic>(msg =>
                {
                    var message = String.Format("{0}: {1}", msg.UserName, msg.Message);
                    Messages.Items.Add(message);
                    Messages.UpdateLayout();
                    Messages.ScrollIntoView(Messages.Items[Messages.Items.Count - 1]);
                    Messages.UpdateLayout();
                });

            PSBClient.Publish(new ChatTopic { Message = "add-user", UserName = "Windows Phone" });

            PSBClient.OnDisconnect = () =>
            {
                PSBClient.Publish(new ChatTopic { Message = "remove-user", UserName = "Windows Phone" });
            };
        }

        private void txtMessage_KeyUp(object sender, KeyEventArgs e) {
            if (e.Key == Key.Enter)
                sendBtn_Click(sender, null);
        }
    }
}